package com.jacky.demo.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;

import com.jacky.demo.R;

/**
 * 拥有2个屏的scrollview
 */
public class TwoScrollView extends ScrollView {

    public TwoScrollView(Context context) {
        super(context);
        init(context, null);
    }

    public TwoScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public TwoScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public TwoScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TwoScrollView);
        setHeaderBackground(a.getDrawable(R.styleable.TwoScrollView_topSpaceBackground));
        setHeaderHeight(a.getDimensionPixelSize(R.styleable.TwoScrollView_topSpaceHeight, 0));
        a.recycle();

        setVerticalScrollBarEnabled(false);
    }

    public void setOnScrollListener(OnScrollListener listener) {
        this.mListner = listener;
    }
    private OnScrollListener mListner;

    private Drawable mHeaderBg;
    private int mheaderHeight;

    public void setHeaderHeight(int headerHeightPiexl) {
        mheaderHeight = headerHeightPiexl;
    }
    public void setHeaderBackground(Drawable drawable) {
        mHeaderBg = drawable;
    }

    private boolean isTouch, isFirstView = true;
    private int firstHeight, firstOffset;
    private int lastScrollY;
    private int lastClickY, curY;

    /**
     * 获取第一个view与第2个view之间切换的临界值
     * @return
     */
    private int getLine() {
        boolean l;
        if(curY > 0) { //往上滑
            l = true;
        } else  if(curY < 0) { //往下滑
            l = false;
        } else {
            l = isFirstView; //点击的逻辑处理
        }
        if(l) {
            return firstOffset + getHeight() / 3;
        } else {
            return firstHeight - getHeight() / 4;
        }
    }

    private Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
            if(!isTouch && lastScrollY == getScrollY()) { //没有继续滚动，则处理逻辑
                /*
                 * 第一个view 的底部是否处理VIEW之间的临界线，
                 * 底部在临界线之上，则显示第一个view的界面
                 * 底部在临界线之下，则显示第二个view的界面
                 */
                int line = getLine();
                if(lastScrollY > firstOffset && lastScrollY <= line) {
                    isFirstView = true;
                    smoothScrollTo(0, firstOffset);
                } else if(lastScrollY > line && lastScrollY < firstHeight) {
                    isFirstView = false;
                    smoothScrollTo(0, firstHeight);
                }
            }
        }
    };

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

            ViewGroup group = (ViewGroup) getChildAt(0);
            View firstView = group.getChildAt(0);
            View secondView = group.getChildAt(1);

        int height = getMeasuredHeight();
            firstHeight = firstView.getHeight();
            firstOffset = firstHeight - height;
        if(secondView != null) {
            secondView.setMinimumHeight(height);
        }
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        lastScrollY = t;
        if(mListner != null) {
            mListner.onScroll(isFirstView, curY > 0, t, getLine());
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if(mHeaderBg != null && getScrollY() < 0) {
            mHeaderBg.setBounds(0, getScrollY(), getWidth(), mheaderHeight + getScrollY());
            mHeaderBg.draw(canvas);
        }
        super.onDraw(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_MOVE :
                curY = (int) (lastClickY - ev.getY());
                break;
            case MotionEvent.ACTION_UP :
                isTouch = false;
                curY = (int) (lastClickY - ev.getY());
                postDelayed(mRunnable, 100); //手机离开屏幕后，判断是否滚动停止
                break;
            case MotionEvent.ACTION_DOWN:
                isTouch = true;
                lastClickY = (int) ev.getY();
                isFirstView = getScrollY() <= firstOffset;
                break;
        }
        return super.onTouchEvent(ev);
    }

    @Override
    protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
        isTouch = isTouchEvent;
        if(!isTouchEvent) {
            deltaY = compluteDelta(deltaY, scrollY);
            postDelayed(mRunnable, 100); //手机离开屏幕后，判断是否滚动停止
        }
        return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
    }

    private int compluteDelta(int deltaY,int scrollY) {
        if(deltaY > 0) { //往上滑的处理逻辑
            if(deltaY + scrollY > firstOffset && scrollY < firstHeight) {
                deltaY = firstOffset - scrollY;
                if(deltaY < 0) deltaY = 0;
            }
        } else if(deltaY < 0) { //往下滑的处理逻辑
            if(scrollY >= firstHeight && deltaY + scrollY < firstHeight) {
                deltaY = firstHeight - scrollY;
            }
        }
        return deltaY;
    }

    public interface OnScrollListener {
        /**
         * @param isFirst true 展示第一个界面
         * @param upScroll true 上滑，下滑
         * @param scrollY 当前scrollv滚动的Y值
         * @param line view与view之间切换的临界线
         */
        void onScroll(boolean isFirst, boolean upScroll, int scrollY, int line);
    }
}
